import _ from 'lodash';
import { ipcMain, Event, BrowserWindow, app } from 'electron';
import express, { Express } from 'express'
import IElectronModule from './bg_base';
import { Server } from 'http';
import { AddressInfo } from 'net';


export const HTTP_BEGIN = "http-begin";
export const HTTP_BEGIN_RET = "http-begin-ret";
export const HTTP_END = "http-end";
export const HTTP_END_RET = "http-end-ret";

class HttpServer implements IElectronModule {

    private win?: BrowserWindow;
    private app?: Express;
    private server?: Server;

    install(win: Electron.BrowserWindow): void {

        ipcMain.on(HTTP_BEGIN, this.httpBegin.bind(this));
        ipcMain.on(HTTP_END, this.httpEnd.bind(this));

    }

    private httpBegin(event: Event, { post = 8081 }: { post?: number } = {}) {
        if (!this.app) {
            this.app = express();
            this.app.use("/res", express.static("res"));
        }
        this.server = this.app.listen(post, () => {
            if(this.server){
            let address = this.server.address() as AddressInfo;
            console.log(`启动网站服务，端口：${post}。地址：${address.address}`) ;
            }
            else{

            console.log(`启动网站服务，端口：${post}。`) ;
            }       
        });
        event.sender.send(HTTP_BEGIN_RET, {
            status: "success",
            message: `启动网站服务，端口：${post}。`
        });
    }

    private httpEnd(event: Event) {
        if (this.server) {
            this.server.close();
            this.server = undefined;
            console.log(`关闭网站服务。`)
        }
    }

    /**
     * 获取网站是否在运行中。
     * @param event 
     * @param param1 
     */
    private isHttpOn(event: Event, { post = 8081 }: { post?: number } = {}) {
        if (this.server) {
            this.server.address;
            this.server = undefined;
            console.log(`关闭网站服务，端口：${post}。`)
        }
    }
}

export default new HttpServer();